const fs = require("fs");
const xlsx = require("node-xlsx");

const app = {
  rowToIdObj: {},
  fileArr: [],
  readDirFn() {
    // 同步读取上级目录下的所有文件到files中
    const files = fs.readdirSync("./lang");
    // console.log(files);
    return files;
  },
  fileArrFn(a, index, fileName) {
    let i = 0;
    for (const key in a.el) {
      if (Object.hasOwnProperty.call(a.el, key)) {
        const ei = a.el[key];
        // console.log("ei", ei);
        for (const key2 in ei) {
          if (Object.hasOwnProperty.call(ei, key2)) {
            const ej = ei[key2];
            // console.log("ej", ej);
            if (index === 0) {
              if (i == 0) {
                this.fileArr.push(["ID", "键1", "键2", "页面说明", fileName]);
              }
              this.fileArr.push([++i, key, key2, "说明", JSON.stringify(ej)]);
              this.rowToIdObj[key + "_" + key2] = i;
            } else {
              if (i == 0) {
                this.fileArr[i].push(fileName);
                // this.fileArr[i].push(fileName + " " + this.fileArr[i].length);
                i++;
              } else {
              }
              console.log("this.fileArr[i]", this.fileArr[i]);
              if (this.fileArr[this.rowToIdObj[key + "_" + key2]]) {
                this.fileArr[this.rowToIdObj[key + "_" + key2]][4 + index] =
                  JSON.stringify(ej); // + " " + key + "_" + key2;
              }
            }
          }
        }
      }
    }
  },
  // 读取文件函数
  async readFileFn(filePath) {
    console.log("读取开始。");
    // 同步读取
    var data = fs.readFileSync(filePath);
    // console.log("同步读取: " + data.toString());
    return data.toString().split("exports.default = ")[1];

    console.log("读取结束。");
  },
  async main() {
    var fileNameList = this.readDirFn("./lang/");
    for (let i = 0; i < fileNameList.length; i++) {
      const item = fileNameList[i];
      if (item) {
        let f = "./lang/" + item;
        let fileStr = await this.readFileFn(f);
        let a;
        eval("a=" + fileStr);
        await this.fileArrFn(a, i, item);
      }
    }
    this.xlsxFn();
  },
  xlsxFn(data) {
    data = [
      {
        name: "sheet1",
        data: this.fileArr,
      },
    ];
    // 写xlsx
    var buffer = xlsx.build(data);
    var time = new Date().getTime();
    fs.writeFile("./resut" + time + ".xls", buffer, function (err) {
      if (err) throw err;
      console.log("Write to xls has finished");

      // 读xlsx
      var obj = xlsx.parse("./" + "resut" + time + ".xls");
      // console.log(JSON.stringify(obj));
    });
  },
};

// 执行主函数
app.main();
